<?php
namespace App\Admin\Controllers\Operation;

use App\Importer\Operation\ProfitSkuImporter;
use App\Jobs\Operation\ProfitSkuUp;
use App\Models\AmazonAds\AdsError;
use App\Models\Basics\SysCountry;
use App\Models\Operation\ProfitSku;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class AdsSyncErrorUploadController extends AdminController{

    protected $title = '上传文件';

    protected function grid()
    {
        return view('operation.ads-sync-error-upload.index');
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file){
        try{
            $data = Excel::toArray(new ProfitSkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            foreach($data as $row){
                $count++;
                $_country = $row[0] ? trim($row[0]) : '';
                $errorField = $row[1] ? trim($row[1]) : '';
                $skuCode = $row[2] ? trim($row[2]) : '';
                if(!$_country || !$errorField || !$skuCode){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $key = $_country.'-'.$errorField;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }

                $country = strtoupper($_country);
                $countryId = SysCountry::getIdByCountry($country);
                if(!$countryId){
                    $errors[$count] = $_country.'系统不存在该国家';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($skuCode,'id');
                if(!$pSkuId){
                    $errors[$count] = $skuCode.'系统不存在该sku';
                    continue;
                }

                //更新
                $flag = AdsError::query()
                    ->where('country_id', $countryId)
                    ->where('error_field', $errorField)
                    ->update([
                        'sku_code' => $skuCode,
                        'status' => AdsError::STATUS_YES //已处理
                    ]);
                if(!$flag){
                    $errors[$count] = $errorField.'系统匹配异常';
                    continue;
                }
            }

            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
